
const app = getApp()
// 杰理模块
var JlModel;
var OTAConfig;
var UpgradeType;

Page({

  data: {
    path: "",
    fileSize: "",
    isOTAing: false,
    otaProgressText: "",
    fileInfo: "",
    fileName: "",
    fileArray: [],

    isShowProgress: false,
    mValue: 0,
    mNumber: 0,
    mTimes: 0,
    mOtaFile: "otaUpdate.ufw",
    mFailReason: "ota Fail",
    mOtaResult: 0,
    mStatus: 0,//0:检验中 1:升级中 2:回连 3:升级成功 4:升级失败、
    isShowLoading: false,
    mLoadingText: "加载升级文件",

    showModal: false,
    modalTitle: '开始升级',
    progress: 0,
    vary_width: wx.getSystemInfoSync().windowWidth * 0.5,
  },
  upgradeData: new Uint8Array(0),
  otaData: Uint8Array.prototype,
  reconnectingDeviceId: "",

  chooseFile: function () {
    const that = this
    if (app.globalData.deviceInfo.batteryPower < 40) {
      wx.showToast({
        title: "电量较低，请充电",
        icon: 'none',
        duration: 2000
      })
      return
    }
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success(res) {
        console.log("chooseMessageFile:", res.tempFiles)
        var myFileArray = that.data.fileArray
        for (var i = 0; i < res.tempFiles.length; i++) {
          let file = res.tempFiles[i]
          console.log("--->" + file.name)
          myFileArray.push({ id: myFileArray.length, fileItem: file, crc: 0 })
        }
        that.setData({ fileArray: myFileArray })

        let oneFile = myFileArray[0]
        let fileContext = oneFile.fileItem

        let fs = wx.getFileSystemManager()
        let path = fileContext.path;
        let fd = fs.openSync({ filePath: path })
        let uint8 = new Uint8Array(fileContext.size)
        fs.read({
          fd: fd, arrayBuffer: uint8.buffer,
          length: fileContext.size,
          success: _res => {
            let tmp_crc = 0;
            uint8.forEach(it => { tmp_crc += it })
            console.log(fileContext)
            that.upgradeData = uint8
            console.log("------读取文件成功------")
            // setTimeout(() => {
            //   // this.dismissLoadingView()
            //   wx.showToast({ title: '加载成功', icon: 'none' })
            // }, 200)
            fs.closeSync({ fd: fd })

            that.showModal()
            that.startUp()
          }, fail: _res => {
            // that.dismissLoadingView()
            wx.showToast({ title: "加载失败", icon: 'none' })
            fs.closeSync({ fd: fd })

          }
        })

        that.upgradeData = oneFile.fileData
        that.setData({ fileIndex: 0, fileOTA: fileContext, fileSize: fileContext.size, fileCrc: oneFile.crc, mOtaFile: fileContext.name })

      }, fail: e => {
        console.error(e)
        // that.dismissLoadingView()
        wx.hideLoading({
          success: () => {
            wx.showToast({ title: "数据错误", icon: 'none' })
          }
        })
      }
    })
  },
  startUp() {

    const otaConfig = new JlModel.OTAConfig()
    otaConfig.isSupportNewRebootWay = true
    otaConfig.updateFileData = this.upgradeData
    console.log("upgradeData size:" + this.upgradeData.length);

    JlModel.startOTA(otaConfig, {
      onStartOTA: () => {
        this.setData({ isShowProgress: true, mStatus: 0 })
        // setTimeout(()=>{
        // })
      },
      onNeedReconnect: (reConnectMsg) => {
        this.setData({ mValue: 0, mStatus: 2, modalTitle: "回连中..." })
      },
      onProgress: (type, progress) => {
        console.log("onProgress " + progress)
        this.setData({progress: progress})
        if (type == JlModel.UpgradeType.UPGRADE_TYPE_CHECK_FILE) {
          this.setData({ mValue: progress, mStatus: 0,modalTitle:'读取文件...' })
        }
        if (type == JlModel.UpgradeType.UPGRADE_TYPE_FIRMWARE) {
          this.setData({ mValue: progress, mStatus: 1,modalTitle:'升级中...' })
        }
      },
      onStopOTA: () => {
        this.hideModal()
        this.setData({ mValue: 0, mOtaResult: 0, mStatus: 3 })
        wx.showToast({title: '升级成功'})
        wx.setStorageSync('deviceId', null)
        setTimeout(()=>{
          wx.reLaunch({
            url: '/pages/index/index'
          })
        },2000)

        },
      onCancelOTA: () => {
        this.hideModal()
        this.setData({ mValue: 0, mOtaResult: 1, mStatus: 4 })
        // wx.showToast({title: '升级'})
      },
      onError: (error, message ) => {
        this.hideModal()
        this.setData({ mValue: 0, mOtaResult: 1, mStatus: 4, mFailReason: message })
        wx.showToast({title: '升级失败:'+error})
        wx.setStorageSync('deviceId', null)
        setTimeout(()=>{
          wx.reLaunch({
            url: '/pages/index/index'
          })
        },2000)
      }
    })
  },
  showModal: function () {
    this.setData({
      showModal: true
    });
  },
  hideModal: function () {
    this.setData({
      showModal: false,
      progress: 0  // 重置进度条
    });
  },
  onLoad() {
    require('../../../lib/index',(mod)=>{
      JlModel = mod
    }, ({ errMsg, mod }) => {
      console.error(`path: ${mod}, ${errMsg}`)
    })
  },
  onShow() {
    console.warn("ota开启");
    app.globalData.isOTA = true
    wx.setKeepScreenOn({
      keepScreenOn: true,
      success() {
        console.log('屏幕保持常亮设置成功');
      },
      fail(err) {
        console.error('屏幕保持常亮设置失败', err);
      }
    });
  },
  onUnload() {
    console.warn("ota关闭");
    app.globalData.isOTA = false
    // 当离开页面时，可以关闭屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: false,
      success() {
        console.log('屏幕常亮设置已关闭');
      }
    });
  }

})